package com.cqw.handers;

import com.cqw.enums.BaseEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-07-12 10:45
 * @Description:
 */
public abstract class BaseEnumHandler<T extends BaseEnum> extends BaseTypeHandler<T> {


    /**
     * 通过枚举对象得到数字
     *
     * @param enumEntity
     * @return
     */
    public abstract Integer getCode(T enumEntity);


    /**
     * 通过数字得到枚举对象
     *
     * @param code
     * @return
     */
    public abstract T getEnumEntity(int code);


    public T getObject(int code) {
        return getEnumEntity(code);
    }


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, getCode(parameter));
    }

    /**
     * Gets the nullable result.
     *
     * @param rs         the rs
     * @param columnName Colunm name, when configuration <code>useColumnLabel</code> is <code>false</code>
     * @return the nullable result
     * @throws SQLException the SQL exception
     */
    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getObject(rs.getInt(columnName));
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getObject(rs.getInt(columnIndex));
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getObject(cs.getInt(columnIndex));
    }
}
